package com.kzw.dao;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.kzw.entity.User;

import my.db.Page;
import my.db.QueryHelper;

public class UserDao {

	public User get(Long id) {
		String sql = "select * from user where id=?";
		return QueryHelper.queryUnique(User.class, sql, id);
	}

	public User findByName(String name) {
		String sql = "select * from user where uname=?";
		return QueryHelper.queryUnique(User.class, sql, name);
	}
	
	public User findByID(Long id) {
		String sql = "select * from user where id=?";
		return QueryHelper.queryUnique(User.class, sql, id);
	}
	
	public void InsertUser(String name,String pwd,String email) {
		String sql = "insert into user values(null,?,?,?,?,?)";
		QueryHelper.update(sql,name,pwd,email,70000000000L,new Date());
	}
	
	public void InsertUser(String name,String pwd,String email,Long money) {
		String sql = "insert into user values(null,?,?,?,?,?)";
		QueryHelper.update(sql,name,pwd,email,money,new Date());
	}
	
	public void update(User a) {
		String sql = "update user set uname=?,passwd=?,email=?,money=? where id=?";
		QueryHelper.update(sql,a.getUname(),a.getPasswd(),a.getEmail(),a.getMoney(), a.getId());
	}
	public void delete(long id) {
		String sql = "delete from user where id=?";
		QueryHelper.update(sql, id);	
	}
	/**
	 * 分页查询
	 * */
	public Page<User> findPage(Page<User> page, String uname) {
		List<Object> params = new ArrayList<>();
		String sql = "select * from user";
		if(StringUtils.isNotBlank(uname)) {
			sql += " where uname like ?";
			params.add("%"+uname+"%");
		}
		List<User> data = QueryHelper.queryPage(User.class, sql, page.getPage(), page.getLimit(), params.toArray());
		page.setData(data);
		
		String sql2 = sql.replaceFirst("select .*? from", "select count(*) from");
		Long cnt = QueryHelper.stat(sql2, params.toArray());
		page.setCount(cnt);			
		return page;
	}
}
